<template>
  <a-carousel
    ref="carousel"
    class="carousel"
    :dots="false"
    :dot-position="'right'"
    :autoplay="true"
    :autoplaySpeed="8000"
    :easing="'ease'"
    style="overflow: hidden"
    v-bind="attrs"
    v-if="dataSource && dataSource.length"
  >
    <div v-for="(item, index) of dataSource" :key="item.key">
      <div :style="slideWrapStyle">
        <template v-if="Array.isArray(item)">
          <slot v-for="(subItem, subIndex) of item" :scope="subItem" :index="subIndex" />
        </template>
        <slot v-else :scope="item" :index="index" />
      </div>
    </div>
  </a-carousel>
  <a-empty v-else />
</template>

<script>
import AEmpty from '../Empty/index.vue';
import { isNumber } from '../../utils/dataType.js';

function getKey(i) {
  return (Number(String(Math.random()).slice(2)) + Date.now() + i).toString(36);
}
export default {
  name: 'AntdCarousel',
  components: { AEmpty },
  props: {
    direction: { type: String, default: 'vertical' /* horizontal,vertical */ },
    dataList: { type: Array, default: () => [] },
    slideWrapStyle: { type: Object, default: () => ({}) },
    slidesPerView: {
      type: Number,
      default: 1,
      validator: (v) => typeof v === 'number' && v > 0,
    },
  },
  computed: {
    attrs() {
      const dir = { horizontal: 'bottom', vertical: 'right' };
      return Object.assign({}, this.$attrs, {
        dotPosition: this.$attrs.dotPosition || dir[this.direction] || dir.vertical,
      });
    },
    dataSource() {
      let { dataList, slidesPerView } = this;
      slidesPerView = parseInt(slidesPerView) || 1;
      if (!dataList || !dataList.length || !isNumber(slidesPerView) || slidesPerView < 1) {
        return [];
      }
      const rmd = dataList.length % slidesPerView;
      if (rmd !== 0) {
        dataList = dataList.concat(dataList.slice(0, length - rmd));
      }
      if (slidesPerView > 1) {
        if (dataList.length / slidesPerView === 1) {
          dataList = [].concat(dataList, dataList);
        }
        const list = dataList.slice(0);
        return list.reduce((res, item, index) => {
          const listItem = list.splice(0, slidesPerView).map((item, inx) => {
            inx = index * slidesPerView + inx;
            return Object.assign({}, item, { key: getKey(inx), index: inx });
          });
          listItem.key = getKey(index);
          res.push(listItem);
          return res;
        }, []);
      } else {
        return dataList;
      }
    },
  },
};
</script>

<style lang="less"></style>
